package a.b.reggie.controller;

import a.b.reggie.common.R;
import a.b.reggie.pojo.AddressBook;
import a.b.reggie.service.IAddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/addressBook")
@Slf4j
public class AddressBookController {

    @Autowired
    private IAddressBookService addressBookService;

    /**
     * 获取地址集合
     * @return
     */
    @GetMapping("/list")
    public R<List<AddressBook>> getList(){
        List<AddressBook> list = addressBookService.list();
        return R.success(list);
    }

    /**
     * 添加地址
     * @param addressBook
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody AddressBook addressBook){
        //获取当前用户手机号
        Long phone = Long.valueOf(String.valueOf(request.getSession().getAttribute("user")));
        addressBookService.saveOne(phone,addressBook);
        return R.success("添加成功");
    }

    /**
     * 根据id查地址
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<AddressBook> getById(@PathVariable Long id){
        log.info("id"+id);
        AddressBook byId = addressBookService.getById(id);
        return R.success(byId);
    }

    /**
     * 修改地址
     * @param addressBook
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody AddressBook addressBook){
        addressBookService.updateById(addressBook);
        return R.success("修改成功");
    }

    /**
     * 修改默认地址
     * @return
     */
    @PutMapping("/default")
    public R<String> setDefault(@RequestBody Map map){
        log.info("id"+map);
        Long id = Long.valueOf(String.valueOf(map.get("id")));
        addressBookService.setDefault(id);
        return R.success("修改成功");
    }

    /**
     * 获取默认地址
     * @return
     */
    @GetMapping("/default")
    public R<AddressBook> getDefault(){
       AddressBook addressBook = addressBookService.getDefault();
        return R.success(addressBook);
    }

    /**
     * 删除地址
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> dalete(Long ids){
        addressBookService.removeById(ids);
        return R.success("删除成功");
    }

    

}
